package com.stockz.watchlist.manager;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.stockz.watchlist.dao.WatchListDao;
import com.stockz.watchlist.model.WatchList;

@Service
public class WatchListManagerImpl implements WatchListManager {

	@Autowired
	private WatchListDao watchListDao;
	private List<String> allWatchListName = new ArrayList<String>();
	
	public List<String> getAllWatchListName() {
		synchronized(allWatchListName){
			if(allWatchListName == null || allWatchListName.isEmpty()){
				allWatchListName = watchListDao.getAllWatchListName();
			}
			return allWatchListName;
		}
	}

	public WatchList get(Long id) {
		return watchListDao.get(id);
	}
	
	public WatchList get(String name){
		return watchListDao.get(name);
	}

	@Transactional
	public void remove(WatchList watchList) {
		synchronized(allWatchListName){
			watchListDao.remove(watchList);
			allWatchListName.remove(watchList.getName());
		}
	}

	@Transactional
	public void persist(WatchList watchList) {
		synchronized(allWatchListName){
			watchListDao.persist(watchList);
			allWatchListName.add(watchList.getName());
		}
	}

	@Transactional
	public WatchList merge(WatchList watchList) {
		synchronized(allWatchListName){
			String previousName = watchListDao.getWatchListNameById(watchList.getId());
			WatchList managed = watchListDao.merge(watchList);
			allWatchListName.remove(previousName);
			allWatchListName.add(managed.getName());
			return managed;
		}
	}
}
